
//
//  LotteryHallViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#define NULLString(string) ((![string isKindOfClass:[NSString class]])||[string isEqualToString:@""] || (string == nil) || [string isEqualToString:@""] || [string isKindOfClass:[NSNull class]]||[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
#import "JddLotteryHallViewController.h"
#import "JddCommonFunction.h"
#import "JddViewControllerManager.h"
#import "JddUserProfile.h"
#import "SBJsonParser.h"
#import "JddSecurity.h"
#import "JddGlobal.h"
#import "JddNavigationBar.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "AdDetailViewController.h"
#import "NoticeViewController.h"
#import "Reachability.h"
#import "ConstHeader.h"
//--------------------新加入的---------------
#import "SDCycleScrollView.h"
#import "JddlotCell.h"
#import "Masonry.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
static BOOL done;

//#import
@interface JddLotteryHallViewController ()<SDCycleScrollViewDelegate,TopViewDelegate>
{
    EGORefreshTableHeaderView *_refreshView;
    BOOL _isLoading;
    //广告的数组
    NSMutableArray *_adArray;
    //广告的位置
    UIScrollView *sView;
    
    BOOL canGoRight;
    UIPageControl *pageControl;
    NSInteger pageNo;
    NSArray *contentArr;
    NSMutableArray *contentArray;//存存储图片的数组
//    NSTimer *timer;
    NSMutableDictionary *_plistInfo;
    UIImageView *_logoView;
    UILabel *_customLab;

    BOOL _lastLoginStatus;
}
//--------------------新加入的---------------
@property(nonatomic,strong)SDCycleScrollView *headerView;
@property(nonatomic,strong)NSMutableArray *caizhongdata;


@end

@implementation JddLotteryHallViewController
@synthesize ssqLotteryIssue;
@synthesize dltLotteryIssue;
@synthesize selectFiveLotteryIssue;

@synthesize fc3dIssue;
@synthesize pl3Issue;
@synthesize pl5Issue;
@synthesize issue7l;
@synthesize issue7x;
@synthesize bdIssueID;
@synthesize count;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddLotteryHallViewController);

//--------------------------新加---------------------------

-(NSMutableArray *)caizhongdata
{
    if (_caizhongdata == nil) {
        _caizhongdata = [[NSMutableArray alloc]init];
    }
    return _caizhongdata;
}
//- (void)bannerBackGroundThread{
//    @autoreleasepool {
//        timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(moveAdImage:) userInfo:nil repeats:YES];
//        
//        done = NO;
//        do{
//            [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
//        }while(!done);
//    }
//}

-(void)refresh2{
    [self startquery];
}


- (void)pickdigitNumberButtonClicked:(NSString *)code{
    if ([code isEqualToString:@"SSQ"]) {
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SHUANGSEQIU
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    else if ([code isEqualToString:@"CJDLT"]) {
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_DALETOU
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    else if ([code isEqualToString:@"11X5"]) {
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_11s5
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    else if ([code isEqualToString:@"FC3D"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_FC3D fromController:self withObject:nil withObject2:nil];
        
    }
    else if ([code isEqualToString:@"PL3"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_P3 fromController:self withObject:nil withObject2:nil];
    }
    else if ([code isEqualToString:@"PL5"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_P5 fromController:self withObject:nil withObject2:nil];
    }
    else if ([code isEqualToString:@"QLC"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7L fromController:self withObject:nil withObject2:nil];
    }
    else if ([code isEqualToString:@"QXC"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7X fromController:self withObject:nil withObject2:nil];
    }
    else if([code isEqualToString:@"SFC"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SFC
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    else if([code isEqualToString:@"RXJ"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_RX9
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    else if ([code isEqualToString:@"11YDJ"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_11YDJ fromController:self withObject:nil withObject2:nil];
    }
    else if ([code isEqualToString:@"CQSSC"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_CQSS fromController:self withObject:nil withObject2:nil];
    }else if([code isEqualToString:@"JCZQ"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SPORT
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }else if([code isEqualToString:@"JCLQ"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_BASKETBALL
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
    else if ([code isEqualToString:@"BJDC"]){
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_BD
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self.navigationItem setHidesBackButton:YES];
    
    _customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    _customLab.backgroundColor = [UIColor clearColor];
    [_customLab setText:@"多多彩票"];
    _customLab.textAlignment = NSTextAlignmentCenter;
    [_customLab setTextColor:[UIColor whiteColor]];
    _customLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
    self.navigationItem.titleView = _customLab;
    
    _logoView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 65, 25)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_logoView];
    
    NSDictionary * dict = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    //self.navigationItem.hidesBackButton = YES;
  
    //----------------新加------------------------
    
//    NSArray *image = @[@"http://admin.tcaio2o.com/images/app/1@2x.png",@"http://admin.tcaio2o.com/images/app/2@2x.png"];
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH,180);
    view.backgroundColor = [UIColor whiteColor];
//    self.headerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 140) shouldInfiniteLoop:YES imageNamesGroup:image];
//    
    self.headerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 140)
                                                         delegate:self
                                                 placeholderImage:[UIImage imageNamed:@"banner_holder"]];
    self.headerView.userInteractionEnabled = YES;
    self.headerView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    self.headerView.pageControlAliment =  SDCycleScrollViewPageContolAlimentCenter;
    self.headerView.autoScrollTimeInterval = 5.0;
    self.headerView.backgroundColor = [UIColor clearColor];
    [view addSubview:self.headerView];
    self.tableView.backgroundColor = UIColorFromRGB(0xf7f7f7);
    self.tableView.tableHeaderView = view;
    
    
    UIImageView *imageview = [[UIImageView alloc]init];
    [imageview setImage:[UIImage imageNamed:@"ring"]];
    [view addSubview:imageview];
    
    UILabel *labelinfo = [[UILabel alloc]init];
    labelinfo.text = @"竞猜周五038比赛取消";
    labelinfo.font = [UIFont systemFontOfSize:12];
    labelinfo.textColor =UIColorFromRGB(0xaaaaaa);
    [view addSubview:labelinfo];
    
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).with.offset(15);
        make.top.equalTo(self.headerView.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(12, 15));
    }];
    [labelinfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageview.mas_right).with.offset(10);
        make.top.equalTo(self.headerView.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-25, 15));
    }];
    //----------------end------------------------


    
    //----------------end------------------------

    //初始化信息
    [self initJddData];//zbj add
    
    [self loadServerData];
    
    _lastLoginStatus = [JddCommonFunction isLogin];
    
    _adArray = [[NSMutableArray alloc] init];
    realresult = [[NSMutableArray alloc] init];
    dataArray = [[NSMutableArray alloc] init];
    contentArray = [[NSMutableArray alloc] init];
    //_tableView.bounces = NO;
    
    if (!sView) {
        //remove ad by rainy HEIGHT→0
        sView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 0/*HEIGHT*/)];
        sView.pagingEnabled = YES;
        sView.showsHorizontalScrollIndicator = NO;
        sView.bounces = NO;
        sView.delegate = self;
    }
    if (!pageControl) {
        pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, HEIGHT-10, 320, 10)];
        
        pageControl.currentPage = 0;
        pageControl.backgroundColor = [UIColor colorWithRed:117/255 green:117/255 blue:117/255 alpha:0.5];
        pageControl.backgroundColor = [UIColor clearColor];
        
        pageNo = 0;
        canGoRight = YES;
    }
    [self loadCellContent];
    
    
//    if ([self.fromController class] == [JddLoginViewController class]) {
//        [self.navigationItem setHidesBackButton:YES];
//    }
    querystate = false;
    
    //如果是自动登录 check一下用户名和密码
    if ([JddCommonFunction isLogin])
        [self checkUserAndPassword];
    /*
     //遍历存储图片的目录,图片存储是SDWebImage第三方存储的
     contentArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self filePath1:@"com.hackemist.SDWebImageCache.default"] error:NULL];
     //在文件中的存储图片的顺序是反的，所以要逆序一下
     for (int i = contentArr.count -1; i>=0; i--) {
     //[contentArray addObject:[contentArr objectAtIndex:i]];
     }
     */
    [self getDate];
    if (IOS7) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 90, 0, 0)];
    }
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,0)];
    self.tableView.tableFooterView = v;

    [self.tableView setSeparatorColor:SeparatorLineColor];
    [self.tableView addHeaderWithTarget:self action:@selector(loadServerData)];
}

- (void)loadServerData {
    if ([JddCommonFunction isLogin]) {
        //获取轮播
        [self getlunbo];
        //获取彩种
        [self getcaizhon];
        //记录用户信息
        [self sendUserInfo];//zbj add
        //获取用户信息
        [self queryUserInfo];//zbj add
        //获取彩店信息
        [self queryShopInfo];//zbj add
        //获取版本号
        [self getVersion];//zbj add
    }
}

//从沙盒中获取广告数据
- (BOOL)getBannerDataFromLocal{
    BOOL ret = NO;
    if (!_plistInfo) {
        _plistInfo = [[NSMutableDictionary alloc] init];
    }
    [_plistInfo removeAllObjects];
    [_plistInfo addEntriesFromDictionary:[JddCommonFunction getBannerPicUrlPlist]];
    if (_plistInfo.count > 0) {
        ret = YES;
    }
    return ret;
}


#pragma mark 广告栏的回调方法
//
////广告栏的回调方法
//- (void)AdOperationResult:(NSData *)data
//{
//    if (data) {
//        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        
//        _adArray = [result[@"Data"]objectFromJSONString];
//        [JddCommonFunction savePlistInfo:_adArray];
//        sView.contentSize = CGSizeMake(320*_adArray.count, HEIGHT);
//        pageControl.numberOfPages = _adArray.count;
//        [_tableView reloadData];
//        //定时器
//        //引导页面消失后，创建定时器且放入后台线程中，让其runloop
//        if (!timer) {
//            [NSThread detachNewThreadSelector:@selector(bannerBackGroundThread) toTarget:self withObject:nil];
//        }
//    }
//}
//
//
////广告移动方法(每2秒钟执行一次)
//- (void)moveAdImage:(NSTimer *)tm
//{
//    //NSLog(@"currentPage = %d, pageNo = %d",pageControl.currentPage,pageNo);
//    if ((1 == pageControl.numberOfPages) || (0 == pageControl.numberOfPages) ) {
//        //当只有一个图片的时候，不处理。
//        sView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"banner_default_icon"]];
//    }else{
//        pageControl.currentPage = pageNo;
//        if (canGoRight) {
//            if (pageControl.currentPage < (pageControl.numberOfPages - 1)) {
//                [sView setContentOffset:CGPointMake(320*(++pageNo), 0) animated:YES];
//            }else{
//                canGoRight = NO;
//                [sView setContentOffset:CGPointMake(320*(--pageNo), 0) animated:YES];
//            }
//        }else{
//            if (pageControl.currentPage > 0) {
//                [sView setContentOffset:CGPointMake(320*(--pageNo), 0) animated:YES];
//            }else{
//                canGoRight = YES;
//                [sView setContentOffset:CGPointMake(320*(++pageNo), 0) animated:YES];
//            }
//        }
//    }
//}

- (void)loadBannerBtns{
    NSArray *keyArr = [_plistInfo allKeys];
    for (id object in keyArr) {
        NSInteger index = [[object substringFromIndex:6] integerValue];
        NSString *ImaID = [[_plistInfo objectForKey:object] objectForKey:@"ImaID"];
        
        UIButton *imageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        imageBtn.frame = CGRectMake(320*index, 0, 320, HEIGHT);
        if ([JddCommonFunction getBannerFileName:ImaID withPath:[self getBannerImgPath]]) {
            [imageBtn setImage:[UIImage imageWithContentsOfFile:[JddCommonFunction getBannerFileName:ImaID withPath:[self getBannerImgPath]]] forState:UIControlStateNormal];
        }else{
            //默认图片
            [imageBtn setImage:[UIImage imageNamed:@"banner_default_icon"] forState:UIControlStateNormal];
        }
        imageBtn.tag = index+1000;
        [imageBtn addTarget:self action:@selector(adImageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [sView addSubview:imageBtn];
    }
}
#pragma mark -- tableviewdelgate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 20;
    }else
    {
        return 10;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *hedview = [[UIView alloc]init];
        hedview.backgroundColor = UIColorFromRGB(0xf7f7f7);
        UILabel *label = [[UILabel alloc]init];
        label.text = @"彩种";
        label.font =[UIFont systemFontOfSize:12];
        label.textColor = UIColorFromRGB(0x222222);
        label.frame = CGRectMake(20, 0, SCREEN_WIDTH-20, 20);
        [hedview addSubview:label];
        
        UILabel *line = [[UILabel alloc]init];
        line.backgroundColor = UIColorFromRGB(0xdd161b);
        line.frame = CGRectMake(10, 5, 3, 10);
        [hedview addSubview:line];
        return hedview;
    }else
    {
        return nil;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOTTERY_OPEN
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 200;
    }
    else{
        return 40;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        static NSString *cellIde = @"JddlotCell";
        JddlotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JddlotCell"];
        if(cell == nil)
        {
            cell = [[JddlotCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIde];
        }
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell model:self.caizhongdata];
        cell.delegate = self;
        return cell;
    }else
    {
        static NSString *cellid= @"twocell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"twocell"];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            UILabel *label = [[UILabel alloc]init];
            label.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"前往开奖大厅";
            label.font = [UIFont systemFontOfSize:14];
            label.textColor = UIColorFromRGB(0x888888);
            [cell addSubview:label];
        }
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;        
        return cell;
    }
}

#pragma mark -- 新加数据请求轮播图
-(void)QueryLunBoInfoOperationResult:(NSData *)result
{
    if (result) {
        SBJsonParser *parser = [[SBJsonParser alloc] init];
        stringresult = [JddDataParser parseLotHallResult:result];
        realresult = [parser objectWithString:stringresult];
        NSMutableArray *imgURLArr = [NSMutableArray array];
        for (NSDictionary *numDic in realresult) {
            [imgURLArr addObject:[numDic objectForKey:@"ImgPath"]];
        }
        if (imgURLArr.count > 0) {
            self.headerView.imageURLStringsGroup = imgURLArr;
            [self.tableView reloadData];
        }
    }
}

#pragma mark -- 新加数据请求彩种
-(void)QuerycaizhonginfoOperationResult:(NSData *)result
{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        SBJsonParser *parser = [[SBJsonParser alloc] init];
        stringresult = [JddDataParser parseLotHallResult:result];
        NSDictionary *numDic  = [parser objectWithString:stringresult];
        NSArray *lotteries = [numDic objectForKey:@"Lotteries"];
        if (lotteries.count > 0) {
            [self.caizhongdata removeAllObjects];
            [self.caizhongdata addObject:lotteries];
            [self.tableView reloadData];
        }
    }
    [self.tableView headerEndRefreshing];
}

- (void)adImageBtnClicked:(UIButton *)button
{
    //NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    //得到完整的文件名
    //NSString *filename=[plistPath stringByAppendingPathComponent:@"bannerPic.plist"];
    //NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    if ([JddCommonFunction checkNetWork] == true) {
        AdDetailViewController *adDetail = [[AdDetailViewController alloc] init];
        NSInteger i = button.tag - 1000;
        
        if (_adArray && _adArray.count > 0) {
            //1、没有网络第一次启动，后来又连接网络   2、网络正常
            
            //这边要先写死了把接口，和webView里请求的接口不一样了
            NSString *linkUrl = [[_adArray objectAtIndex:i]objectForKey:@"LinkUrl"];
            NSString *alt = [[_adArray objectAtIndex:i]objectForKey:@"Alt"];
            //NSString *imageUrl = [[_adArray objectAtIndex:i]objectForKey:@"ImageUrl"];
            //NSString *imaID = [[_adArray objectAtIndex:i] objectForKey:@"ImaID"];
            adDetail.linkUrl = linkUrl;
            adDetail.alt = alt;
            
        }else{
            //网络正常但是没有获取到数据，从缓存中获取数据
            if ([self getBannerDataFromLocal]) {
                //缓存中有数据
                NSArray *keyArr = [_plistInfo allKeys];
                for (id object in keyArr) {
                    //获取对应索引
                    NSInteger index = [[object substringFromIndex:6] integerValue];
                    if (index == i) {
                        adDetail.linkUrl = [[_plistInfo objectForKey:object] objectForKey:@"LinkUrl"];
                        adDetail.alt = [[_plistInfo objectForKey:object] objectForKey:@"Alt"];
                    }
                }
            }else{
                //缓存中没有数据的话不进行赋值，理论上不可能没有数据。
            }
        }
        [self.navigationController pushViewController:adDetail animated:YES];
    }else{
        //没有网络的时候，只能从缓存中获取数据
        AdDetailViewController *adDetail = [[AdDetailViewController alloc] init];
        NSInteger i = button.tag - 1000;
        if ([self getBannerDataFromLocal]) {
            //缓存中有数据
            NSArray *keyArr = [_plistInfo allKeys];
            for (id object in keyArr) {
                NSInteger index = [[object substringFromIndex:6] integerValue];
                if (index == i) {
                    adDetail.linkUrl = [[_plistInfo objectForKey:object] objectForKey:@"LinkUrl"];
                    adDetail.alt = [[_plistInfo objectForKey:object] objectForKey:@"Alt"];
                }
            }
        }else{
            //缓存中没有数据不做处理
            
        }
        [self.navigationController pushViewController:adDetail animated:YES];
    }
}

- (void)initJddData {
    [JddSecurity storeSystemData];
    [[JddGlobalParameter sharedInstance] load];
    JddGlobal *jdd = [JddGlobal sharedInstance];
    jdd.navigationController = self.navigationController;
    [jdd load];
}

//记录用户信息
- (void)sendUserInfo {
    NSString *passWord =  [JddSFHFKeychainUtils getPasswordForUsername:USER_UUID andServiceName:USER_UUID error:nil];
    if (passWord.length == 0)
    {
        JddSendUserUniqueIdentifierOperation *operation = [[JddSendUserUniqueIdentifierOperation alloc] init];
        operation.delegate = self;
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}
- (void)SendUserUniqueIdentifierOperationResult:(NSData *)result {
    if (result) {
        NSDictionary *d = [result objectFromJSONData];
        NSLog(@"%@", [d objectForKey:@"Data"]);
    }
}
//获取用户信息
- (void)queryUserInfo {
    if ([JddCommonFunction isLogin]) {
        JddQueryUserInfoOperation *operation = [[JddQueryUserInfoOperation alloc] init];
        operation.delegate = self;
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}
//获取彩店信息
- (void)queryShopInfo {
    if ([JddCommonFunction isLogin]) {
        JddQueryLotteryShopInfoOperation *operation = [[JddQueryLotteryShopInfoOperation alloc] init];
        operation.delegate = self;
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}
//-----------新加----------
//获取轮播
-(void)getlunbo
{
    JddQueryLunBoInfoOperation *operation = [[JddQueryLunBoInfoOperation alloc] init];
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
}
//获取彩种
-(void)getcaizhon
{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddQuerycaizhonginfoOperation *operation = [[JddQuerycaizhonginfoOperation alloc] init];
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

//获取用户信息 JddQueryUserInfoOperation 的回调方法
- (void)QueryUserInfoOperationResult:(NSData *)result {
//    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        [JddDataParser parseUserInfoResult:result];
    }
}
//获取彩店信息 JddQueryLotteryShopInfoOperation 的回调方法
- (void)QueryLotteryShopInfoOperationResult:(NSData *)result {
    if (result) {
        if (![JddDataParser parseShopInfoResult:result]) {
//            [JddCommonFunction messageBoxWithMessage:@"获取彩店信息失败"];
        } else {
            [[JddGlobalParameter sharedInstance].dictionary setObject:[JddUserProfile sharedInstance].shopID
                                                               forKey:GLOBAL_PARAMETER_SHOP_ID];
            [[JddGlobalParameter sharedInstance] save];
            [_customLab setText:[JddUserProfile sharedInstance].shopTitle];
            if(!NULLString([JddUserProfile sharedInstance].shopLogo)) {
               [_logoView sd_setImageWithURL:[NSURL URLWithString:[JddUserProfile sharedInstance].shopLogo]];
            }
        }
    } else {
//        [JddCommonFunction messageBoxWithMessage:@"获取彩店信息失败"];
    }
}
//获取版本号
- (void)getVersion {
    //创建更新版本操作
    JddQueryVersionOperation *operation = [[JddQueryVersionOperation alloc] init];
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}
//获取版本号的回调方法
-(void)QueryVersionOperationResult:(NSData *)result{
    if (result) {
        int versionCode = [[[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleVersion"] intValue];
        SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
        @try {
            NSDictionary *dictResult = [jsonParser objectWithData:result];
            int code = [[dictResult objectForKey:@"Code"] intValue];
            if (code == 0) {
                NSArray *temoArray = [jsonParser objectWithString:[dictResult objectForKey:@"Data"]];
                NSDictionary *dictResult22 = [temoArray objectAtIndex:0];
                int newCode = [[dictResult22 objectForKey:@"verCode"] intValue];
                NSArray* newMessage = [dictResult22 objectForKey:@"Message"];
                downLoadURL = [dictResult22 objectForKey:@"apkname"];
                int bupdate = [[dictResult22 objectForKey:@"bupdate"] intValue];
                
                NSString *msg = @"有新的版本可供升级，确定升级？";
                for (NSString *inmsg in newMessage) {
                    msg = [msg stringByAppendingFormat:@"\n%@",inmsg];
                }
                
                if (versionCode < newCode /*&& bupdate == 1*/) {
                    if(bupdate == -1){
                        UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"玩球球更新提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"退出", nil];
                        [alert show];
                    }else{
                        UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                        [alert show];
                    }
                }
            }
        }
        @catch (NSException *e) {
            [JddError sharedInstance].message = e.reason;
        }
    }
}
//提示框
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSString * URLString = @"https://itunes.apple.com/cn/app/jiang-duo-duo-cai-piao/id562188850?mt=8";
        if ([downLoadURL length] > 0) {
            URLString = downLoadURL;
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
    }else if (buttonIndex == 1){
        if ([alertView.title isEqualToString:@"玩球球更新提示"]) {
            exit(0);
        }
    }
}
//进行一次用户名和密码的检查，此功能目的，修改了密码后，重新检验用户名和密码
-(void) checkUserAndPassword
{
    JddLogonOperation *operation = [[JddLogonOperation alloc] init];
    operation.delegate = self;
    operation.userName     = [JddUserProfile sharedInstance].name;
    operation.userPassword = [JddUserProfile sharedInstance].password;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

//
- (void)LogonOperationResult:(NSData *)result
{
    //[JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result)
    {
        NSString *uId = [JddDataParser parseLoginResult:result];
        if (uId.length == 0)
        {
            //            NSString *hintString = [NSString stringWithFormat:@"%@\n(可能密码被修改,如不是本人操作，请联系客服。)",[JddError sharedInstance].message];
            //            [JddCommonFunction messageBoxWithMessage:hintString];
            [JddUserProfile clearMessage];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

- (void)loadCellContent
{
    //    shuangSeQiuCell = [JddLotteryHallItemTableCell getInstanceView];
    //    shuangSeQiuCell.code = @"SSQ";
    //    shuangSeQiuCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_ssq.png"];
    //    shuangSeQiuCell.lotNameImage.text = @"双色球";
    //    shuangSeQiuCell.remainTimeLabel.text = @"2彩豆可中1000万";
    //    shuangSeQiuCell.delegate = self;
    //    shuangSeQiuCell.tagLabel.hidden = NO;
    //    [shuangSeQiuCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    shuangSeQiuCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    //    daLeTouCell = [JddLotteryHallItemTableCell getInstanceView];
    //    daLeTouCell.code = @"CJDLT";
    //    daLeTouCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_dlt.png"];
    //    daLeTouCell.remainTimeLabel.text = @"每周一 三 六 20:30开奖";
    //    daLeTouCell.lotNameImage.text = @"超级大乐透";
    //    daLeTouCell.delegate = self;
    //    daLeTouCell.tagLabel.hidden = NO;
    //    [daLeTouCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    daLeTouCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    elevenSelectFiveCell = [JddLotteryHallItemTableCell getInstanceView];
    elevenSelectFiveCell.code = @"11X5";
    elevenSelectFiveCell.lotNameImage.text =@"11选5";
    elevenSelectFiveCell.remainTimeLabel.text = @"每10分钟开一期 每天开奖78期";
    elevenSelectFiveCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_11five.png"];
    elevenSelectFiveCell.delegate = self;
    elevenSelectFiveCell.tagLabel.hidden = NO;
    [elevenSelectFiveCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    elevenSelectFiveCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    
    
    footballCell = [JddLotteryHallItemTableCell getInstanceView];
    footballCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_jc.png"];
    footballCell.lotNameImage.text = @"竞彩足球";
    footballCell.remainTimeLabel.text = @"天天有比赛 返奖率高达69%";
    footballCell.delegate = self;
    footballCell.code = @"JCZQ";
    footballCell.tagLabel.hidden = YES;
    //    footballCell.tagLabel.hidden = NO;
    //    [footballCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    footballCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    //    bdCell = [JddLotteryHallItemTableCell getInstanceView];
    //    bdCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_bd.png"];
    //    bdCell.lotNameImage.text = @"北京单场";
    //    bdCell.remainTimeLabel.text = @"返奖率高达65% 速来抢钱";
    //    bdCell.delegate = self;
    //    bdCell.code = @"BJDC";
    //    bdCell.tagLabel.hidden = YES;
    
    basketBallCell = [JddLotteryHallItemTableCell getInstanceView];
    basketBallCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_jclq.png"];
    basketBallCell.lotNameImage.text = @"竞彩篮球";
    basketBallCell.remainTimeLabel.text = @"返奖率高达69% 边看比赛边中奖";
    basketBallCell.delegate = self;
    basketBallCell.code = @"JCLQ";
    basketBallCell.tagLabel.hidden = YES;
    
    
    //    sfcCell = [JddLotteryHallItemTableCell getInstanceView];
    //    sfcCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_sfc.png"];
    //    sfcCell.lotNameImage.text = @"胜负彩";
    //    sfcCell.remainTimeLabel.text = @"竞猜14场比赛 最高奖金500万";
    //    sfcCell.delegate = self;
    //    sfcCell.code = @"SFC";
    //    sfcCell.tagLabel.hidden = YES;
    //    sfcCell.tagLabel.hidden = NO;
    //    [sfcCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    sfcCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    
    //    rx9Cell = [JddLotteryHallItemTableCell getInstanceView];
    //    rx9Cell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_rx9.png"];
    //    rx9Cell.lotNameImage.text = @"任选九";
    //    rx9Cell.remainTimeLabel.text = @"竞猜9场比赛 最高奖金500万";
    //    rx9Cell.delegate = self;
    //    rx9Cell.code = @"RXJ";
    //    rx9Cell.tagLabel.hidden = YES;
    //    rx9Cell.tagLabel.hidden = NO;
    //    [rx9Cell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    rx9Cell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    
    fc3dCell = [JddLotteryHallItemTableCell getInstanceView];
    fc3dCell.code = @"FC3D";
    fc3dCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_3d.png"];
    fc3dCell.lotNameImage.text = @"福彩3D";
    fc3dCell.remainTimeLabel.text = @"每天猜3个数 2彩豆可赢1040彩豆";
    fc3dCell.delegate = self;
    fc3dCell.tagLabel.hidden = NO;
    [fc3dCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    fc3dCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    
    //    pl3Cell = [JddLotteryHallItemTableCell getInstanceView];
    //    pl3Cell.code = @"PL3";
    //    pl3Cell.remainTimeLabel.text = @"直选奖1040彩豆 组三346彩豆 组六173";
    //    pl3Cell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_p3.png"];
    //    pl3Cell.lotNameImage.text = @"排列三";
    //    pl3Cell.delegate = self;
    //    pl3Cell.tagLabel.hidden = NO;
    //    [pl3Cell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    pl3Cell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    //    pl5Cell = [JddLotteryHallItemTableCell getInstanceView];
    //    pl5Cell.code = @"PL5";
    //    pl5Cell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_p5.png"];
    //    pl5Cell.lotNameImage.text = @"排列五";
    //    pl5Cell.remainTimeLabel.text = @"天天开奖 2彩豆可中10万彩豆";
    //    pl5Cell.delegate = self;
    //    pl5Cell.tagLabel.hidden = NO;
    //    [pl5Cell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    pl5Cell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    //
    //    n7lCell = [JddLotteryHallItemTableCell getInstanceView];
    //    n7lCell.code = @"QLC";
    //    n7lCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_n7l.png"];
    //    n7lCell.lotNameImage.text = @"七乐彩";
    //    n7lCell.remainTimeLabel.text = @"30选7百万大奖期期开";
    //    n7lCell.delegate = self;
    //    n7lCell.tagLabel.hidden = YES;
    //    n7lCell.tagLabel.hidden = NO;
    //    [n7lCell.tagLabel setTitle:@"新" forState:UIControlStateNormal];
    //    n7lCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    //
    //    n7xCell = [JddLotteryHallItemTableCell getInstanceView];
    //    n7xCell.code = @"QXC";
    //    n7xCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_n7x.png"];
    //    n7xCell.lotNameImage.text = @"七星彩";
    //    n7xCell.remainTimeLabel.text = @"单注最高奖金500万";
    //    n7xCell.delegate = self;
    //    n7xCell.tagLabel.hidden = YES;
    //    n7xCell.tagLabel.hidden = NO;
    //    [n7xCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    //    n7xCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
    n11ydjCell = [JddLotteryHallItemTableCell getInstanceView];
    n11ydjCell.code = @"11YDJ";
    n11ydjCell.lotNameImage.text =@"十一运夺金";
    n11ydjCell.remainTimeLabel.text = @"每10分钟开一期 每天开奖78期";
    n11ydjCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_11ydj"];
    n11ydjCell.delegate = self;
    n11ydjCell.tagLabel.hidden = NO;
    [n11ydjCell.tagLabel setTitle:@"加  奖" forState:UIControlStateNormal];
    n11ydjCell.tagLabel.titleLabel.font = [UIFont systemFontOfSize:10];
    
        cqssCell = [JddLotteryHallItemTableCell getInstanceView];
        cqssCell.code = @"CQSSC";
        cqssCell.lotNameImage.text =@"时时彩";
        cqssCell.remainTimeLabel.text = @"白天72期10分钟一期 夜间48期5分钟一期";
        cqssCell.lotteHallImage.image = [UIImage imageNamed:@"jdd_buy_main_ssc"];
        cqssCell.delegate = self;
}

#pragma mark 滚动视图
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == sView) {
        NSInteger curPage=scrollView.contentOffset.x/320;
        pageControl.currentPage=curPage;
        pageNo = curPage;
    }
}

- (void)rightBtnClicked:(UIButton *)button
{
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    [self.navigationController pushViewController:noticeView animated:YES];
}

//回调函数
-(void)QueryLotteryHallOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        SBJsonParser *parser = [[SBJsonParser alloc] init];
        stringresult = [JddDataParser parseLotHallResult:result];
        realresult = [parser objectWithString:stringresult];
        for (NSDictionary *numDic in realresult){
            if (![[numDic objectForKey:@"Code"] isEqualToString:@"K3"]) {
                [dataArray addObject:numDic];
            }
        }
        querystate = false;
    }
}

-(void)startquery{
    if (!querystate) {
        querystate = true;
        //        JddQueryLotteryHallOperation *operation = [[JddQueryLotteryHallOperation alloc] init];
        //            operation.delegate= self;
        //        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LotteryHall"];
    [MobClick event:@"TAB-BuyHall"];
    
    [self.view setUserInteractionEnabled:YES];
    
    [self setTabBarItemSelect:1];
    
    //显示tabbar
    [self setJddTabBarHidden:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startquery) name:CQSS_MESSAGE object:nil];
    
    //重置viewControolers
    [JddCommonFunction clearViewControllers];
//    querystate = false;
//    if ([JddCommonFunction checkNetWork]) {
//        [JddCommonFunction setWaitingViewHidden:YES fromController:self];
//        [self startquery];
//    }
    //remove ad by rainy
    //    //放入线程池 广告请求
    //    if ([JddCommonFunction checkNetWork]) {
    //        JddAdOperation *operation = [[JddAdOperation alloc] init];
    //        operation.delegate = self;
    //        operation.platformTyp = @"6";
    //        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    //    }else{
    //        //没有网络的时候，从本地获取数据
    //        if (!_plistInfo) {
    //            [self getBannerDataFromLocal];
    //        }
    //
    //        sView.contentSize = CGSizeMake(320*[_plistInfo allKeys].count, HEIGHT);
    //        pageControl.numberOfPages = [_plistInfo allKeys].count;
    //        if (!timer) {
    //            [NSThread detachNewThreadSelector:@selector(bannerBackGroundThread) toTarget:self withObject:nil];
    //        }
    //    }
    
//    [_tableView reloadData];
//    [timer setFireDate:[NSDate distantPast]];//开启定时器
    
    if (![JddCommonFunction isLogin]) {
        [JddViewControllerManager sharedInstance].hideBackItem = YES;
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                fromController:self
                                                                    withObject:nil
                                                                   withObject2:nil];
        return;
    }
    if ([JddCommonFunction isLogin] && !_lastLoginStatus) {
        [self loadServerData];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LotteryHall"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self setJddTabBarHidden:YES];
//    [timer setFireDate:[NSDate distantFuture]];//关闭定时器
}

- (NSString *)filePath:(NSString *)fileName
{
    NSString *path = NSHomeDirectory();
    path = [path stringByAppendingPathComponent:@"Library"];
    path = [path stringByAppendingPathComponent:@"Caches"];
    path = [path stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
        if (fileName && [fileName length]!=0) {
            path = [path stringByAppendingPathComponent:fileName];
        }
    }
    return path;
}
- (NSString *)filePath1:(NSString *)fileName
{
    NSString *path = NSHomeDirectory();
    path = [path stringByAppendingPathComponent:@"Library"];
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
        if (fileName && [fileName length]!=0) {
            path = [path stringByAppendingPathComponent:fileName];
        }
    }
    return path;
}

- (NSInteger)getDate
{
    NSInteger week;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:now];
    week = [comps weekday];
    return week;
}

- (NSString *)getBannerImgPath{
    NSString *bannerImgPath = [[[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"lotteryhall"] stringByAppendingPathComponent:@"banner"] stringByAppendingPathComponent:@"image"];
    
    return [NSString stringWithFormat:@"%@",bannerImgPath];
}

@end
